﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OOAD_Project_Engine.Domain.Entities;
using System.Reflection;
using OOAD_Project_Engine.Foundation.Interfaces;

namespace OOAD_Project_Engine.Domain.Factories
{
    public sealed class EntityFactory : Factory
    {
        ComponentManager manager;
        public EntityFactory(ComponentManager manager)
        {
            this.manager = manager;
        }

        public T Create<T>(string name) where T : Entity
        {
            return Create<T>(new object[] { name });
        }

        public T Create<T>(string name, params IEntityComponent[] components) where T : Entity
        {
            return Create<T>(new object[] { name, components });
        }

        public Entity Create(Type type, string name, params IEntityComponent[] parameters)
        {
            object[] _params = new object[] { name, parameters };

            Type[] types = new Type[_params.Length];
            for (int i = 0; i < _params.Length; i++)
                types[i] = _params[i].GetType();

            MethodInfo mi = this.GetType().GetMethod("Create",new Type[] { _params.GetType() });
            return  mi.MakeGenericMethod(type).Invoke(this, new object[] { _params }) as Entity;
        }

        public T Create<T>(params object[] parameters) where T : Entity
        {
            object o = Create(typeof(T), parameters);
            Entity entity = o as Entity;
            entity.Manager = manager;
            manager.Add(entity);
            return o as T;
        }
    }
}
